package http

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"micro-oauth/datamodels/autherror"
	"micro-oauth/datamodels/params"
	"micro-oauth/service"
	"net/http"
	"strings"
	"time"
)

func apiCodeFromURL(url string) string {
	url = strings.Replace(url, "/", ".", -1)
	return strings.Trim(url, ".")
}

type Middleware = func(http.Handler) http.Handler

func Authorization() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		//token = strings.TrimLeft(token, "Bearer ")  why this show a bug?
		st := time.Now()
		c.Set("start_time", st)
		if len(token) > 7 {
			token = token[7:]
		} else {
			token = ""
		}
		fmt.Println("token:",token)
		if token == "" {
			err := autherror.Unauthorized("no token")
			c.JSON(http.StatusOK, HexErrorToResponse(err))
			c.Abort()
			return
		}

		req := &params.AuthenticateRequest{
			Token:           token,
			CheckPermission: false,
			APICode:         apiCodeFromURL(c.Request.URL.Path),
		}
		resp, err := service.OauthService.Authenticate(c, req)
		if err != nil {
			err := autherror.Unauthorized(err.Error())
			c.JSON(http.StatusOK, HexErrorToResponse(err))
			c.Abort()
			return
		}
		c.Set("user_id", resp.UserId)
		c.Set("partner_id", resp.PartnerId)
		c.Set("scope_id", resp.ScopeId)
		c.Next()
	}
}
